
console.log('获取到span的dom如下')

chrome.runtime.sendMessage({
  from: 'content',
  subject: 'showPageAction',
})

chrome.runtime.onMessage.addListener((msg, sender, response) => {
  // First, validate the message's structure.
  if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
    // Collect the necessary data. 
    // (For your specific requirements `document.querySelectorAll(...)`
    //  should be equivalent to jquery's `$(...)`.)
    var domInfo = '接收到popup消息，这是返回的'

    // Directly respond to the sender (popup), 
    // through the specified callback.
    response(domInfo)
  }
})

/* toast提示 */
function Toast(text) {
  const m = document.createElement('div')
  const toastId = Date.now() + ''
  m.setAttribute('toastId', toastId)
  m.setAttribute('style', 'background: #000;border-radius: 8px;color: #fff;font-size: 28px;left: 50%;max-width: 62.6%;opacity: 0.7;padding: 0 5px;padding: 0.75rem 1rem;position: fixed;text-align: center;top: 20%;transform: translate(-50%, -50%);z-index: 9999999999;');
  m.className = 'Toast'
  m.id = 'jd-toast'
  m.innerHTML = `<div><p>${text}</p><div>`
  document.body.appendChild(m)
  setTimeout(function () {
    const d = 0.5
    m.style.webkitTransition =
      '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in'
    m.style.opacity = '0'
    setTimeout(function () {
      const node1 = document.getElementById('jd-toast')
      if (node1?.getAttribute('toastId') == toastId)
        document.body.removeChild(node1);
    }, d * 1000)
  }, 2000)
}
/* =============================================================================================== 
  操作逻辑：
  1.当快到预定时间，比如09:59分，马上快到10:00
  2.进入摘牌页面，查询摘牌数据
  3.设置好插件参数，并开启插件
  4.插件筛选出符合要求的多个table row
  5.循环查找符合要求的table row中是否有可点击的【摘牌】按钮
  6.如果有则自动执行【摘牌】操作
  7.执行完一条table row后再执行下一条
  8.直到所有满足条件的table row都被执行完摘牌
=============================================================================================== */

var intervalID = null
var intervalDialogID = null
var totalSum = 0
var pickedTotal = 0
// 寻找摘牌按钮并检查按钮点击状态
function searchBtn(setting) {
  console.log('执行searchBtn')
  /* 寻找提交按钮dom */
  let iframeDom = null
  let iframeList = document.getElementsByTagName('iframe')
  for (let i = 0; i < iframeList.length; i++) {
    if (iframeList[i].style.display === '') {
      iframeDom = iframeList[i].contentDocument
      break;
    }
  }

  if (!iframeDom) {
    Toast('非挂牌摘牌页面！')
    return
  }

  var paddingHandler  = (resolveCb) => {
    let p = new Promise((resolve, reject) => {
      intervalDialogID = setInterval(() => {
        let dialogDom = iframeDom.getElementsByClassName('el-dialog__body')
        console.log('等待寻找弹窗')
        if (dialogDom) {
          clearInterval(intervalDialogID)
          resolve(dialogDom)
        }
      }, 10)
    })

    p.then((dialogDom) => {
      let dialogDomTar = Array.from(dialogDom).find(item => {
        return item.style.display !== 'none'
      })
      let labelDoms = dialogDomTar.querySelectorAll('.el-form-item__label')

      let restElecDom = Array.from(labelDoms).find(item => {
        return item.innerHTML.includes('剩余可摘量')
      })
      let priceDom = Array.from(labelDoms).find(item => {
        return item.innerHTML.includes('挂牌方价格')
      })
      let pickDom = Array.from(labelDoms).find(item => {
        return item.innerHTML.includes('摘牌电价')
      })
      let elecDom = Array.from(labelDoms).find(item => {
        return item.innerHTML.includes('摘牌电量')
      })

      let priceValue = priceDom.nextElementSibling.children[0].innerHTML
      let restElecValue = restElecDom.nextElementSibling.children[0].innerHTML
      
      console.log(restElecValue);
      totalSum += parseInt(restElecValue)
      // 如果本次摘牌电量总和大于预计摘牌总电量，那么本次摘牌量为预计摘牌总电量 - 已摘牌量，来进行补齐
      if (totalSum > setting.total) {
        elecDom.nextElementSibling.querySelector('input').value = setting.total - pickedTotal
      } else {
        elecDom.nextElementSibling.querySelector('input').value = restElecValue
        // 累计已摘牌电量
        pickedTotal += restElecValue
      }
      // 模拟oninput事件
      const event = document.createEvent('HTMLEvents')
      event.initEvent('input', false, true)
      // 模拟触发oninput
      elecDom.nextElementSibling.querySelector('input').dispatchEvent(event)

      pickDom.nextElementSibling.querySelector('input').value = priceValue
      
      pickDom.nextElementSibling.querySelector('input').dispatchEvent(event)

      let btnsDom = dialogDom[0].querySelectorAll('.el-button')
      btnsDom[0].click() // 获取电价

      btnsDom[1].click() // 摘牌提交      
      
      resolveCb(elecDom.nextElementSibling.querySelector('input').value)
    })
  }

  // trs满足输入条件的tr，寻找摘牌按钮，并触发点击
  intervalID = setInterval(async () => {
    let completeCount = 0
    chrome.runtime.sendMessage({
      from: 'content',
      type: 'info',
      msg: '正在寻找可摘牌数据'
    })
    console.log('------开始执行------');
    
    let tables = iframeDom.getElementsByClassName('el-table__body-wrapper')
    // 页面中有三个表格，我们需要的表格在第二个
    if (!tables[1]) {
      return
    }
    let trs = tables[1].querySelectorAll('tr')

    let trsCopy = Array.from(trs).filter(item => {
      let period = item.querySelectorAll('td')[5].querySelector('div div').innerHTML
      let price = parseFloat(item.querySelectorAll('td')[7].querySelector('div div').innerHTML)
      // console.log(period, price)
      // console.log('=======', setting.priceMax, price);
      if (period.includes(setting.period) && price >= setting.priceMin && price <= setting.priceMax) {
        return item
      }
    })
    // 按照价格从低到高排序
    trsCopy.sort((a, b) => {
      return a.querySelectorAll('td')[7].querySelector('div div').innerHTML - b.querySelectorAll('td')[7].querySelector('div div').innerHTML
    })

    if (trsCopy.length > 0) {
      let flag = false
      for (let i = 0; i < trsCopy.length; i++) {
        let btn = trsCopy[i].querySelector('.el-button')
        if (btn) {
          await new Promise((resolve, reject) => {
            if (!btn.classList.contains('is-disabled')) {
              console.log('------开始第'+ (i+1) +'次摘牌------');
              console.log('操作行----',trsCopy[i].querySelectorAll('td')[2].querySelector('div>span').innerHTML , trsCopy[i].querySelectorAll('td')[5].querySelector('div').innerHTML, trsCopy[i].querySelectorAll('td')[7].querySelector('div').innerHTML);
              btn.click()
              completeCount++
              // 弹窗出现，填充弹窗并提交
              paddingHandler(resolve)
              console.log(trs[i].querySelectorAll('td')[9].querySelector('div>div').innerHTML);
            } else {
              reject()
            }
          }).then((val) => {
            console.log('------完成第'+ (i+1) +'次摘牌------');
            chrome.runtime.sendMessage({
              from: 'content',
              type: 'info',
              msg: '完成第' + completeCount + '次摘牌: ' + val
            })
            // if (i === trsCopy.length - 1) {
            //   clearInterval(intervalID)
            //   console.log('表内所有数据都已进行摘牌')
            //   chrome.runtime.sendMessage({
            //     from: 'content',
            //     type: 'success',
            //     msg: '完成：表内所有数据都已进行摘牌'
            //   })
            // }
            console.log(completeCount, totalSum, setting.total)
            if (totalSum >= setting.total) {
              // 如果总电量等于或者超过预计摘牌量，那么结束脚本
              console.log(intervalID)
              clearInterval(intervalID)
              console.log('------执行完成------')
              chrome.runtime.sendMessage({
                from: 'content',
                type: 'success',
                msg: '完成：摘牌量达到预计摘牌量'
              })
              flag = true
            }
          }).catch(() => {
            console.log('按钮无法点击')
          })
          if (flag) {
            // console.log('====',i)
            break
          }
        } else {
          console.log('没有找到摘牌按钮')
        }
      }
    } else {
      // clearInterval(intervalID)
      // chrome.runtime.sendMessage({
      //   from: 'content',
      //   type: 'error',
      //   msg: '没有符合时段+电价条件的挂牌'
      // })
      // console.log('没有符合时段+电价条件的挂牌')
    }
    
  }, 100) // 执行频率
}

function stopExecute() {
  totalSum = 0
  pickedTotal = 0
  clearInterval(intervalDialogID)
  clearInterval(intervalID)
}

window.addEventListener('error', function (event) {
  console.log(event)
  chrome.runtime.sendMessage({
    from: 'content',
    type: 'error',
    msg: event.message
  })
})